package us.kg.kotoriforest.springmvc.restful.controller;

import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import us.kg.kotoriforest.springmvc.restful.common.R;
import us.kg.kotoriforest.springmvc.restful.pojo.Employee;
import us.kg.kotoriforest.springmvc.restful.service.EmployeeService;
import us.kg.kotoriforest.springmvc.restful.vo.request.EmployeeAddVo;
import us.kg.kotoriforest.springmvc.restful.vo.request.EmployeeUpdateVo;
import us.kg.kotoriforest.springmvc.restful.vo.response.EmployeeResponseVo;

import java.util.List;

/**
 * @author Kotori rotroutine@163.com
 * @since 2025/2/4
 */
@CrossOrigin
@RestController
@AllArgsConstructor
public class RestfulController {
    private final EmployeeService employeeService;

    @GetMapping("/employee/{id}")
    public R<Employee> getEmployeeById(@PathVariable("id") long id) {
        Employee employee = employeeService.getEmployeeById(id);
        return employee == null ? R.notFound() : R.success(employee);
    }

    @PostMapping("/employee")
    public R<?> addEmployee(@Valid @RequestBody EmployeeAddVo vo /*, BindingResult bindingResult */) {
        // if (bindingResult.hasErrors()) {
        //     Map<String, String> errors = new HashMap<>();
        //     for (FieldError fieldError : bindingResult.getFieldErrors()) {
        //         errors.put(fieldError.getField(), fieldError.getDefaultMessage());
        //     }
        //
        //     return R.error(errors);
        // }

        return employeeService.addEmployee(new Employee(vo)) ? R.success() : R.error();
    }

    @PutMapping("/employee")
    public R<Employee> updateEmployee(@RequestBody @Valid EmployeeUpdateVo vo) {
        return employeeService.updateEmployeeSensitive(new Employee(vo)) ? R.success() : R.error();
    }

    @DeleteMapping("/employee/{id}")
    public R<Employee> deleteEmployeeById(@PathVariable("id") long id) {
        return employeeService.deleteEmployeeById(id) ? R.success() : R.error();
    }

    @GetMapping("/employees")
    public R<List<EmployeeResponseVo>> getEmployees() {
        return R.success(EmployeeResponseVo.of(employeeService.getEmployees()));
    }
}
